package com.msb.dongbao.ums.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.msb.dongbao.ums.dto.UserMemberDto;
import com.msb.dongbao.ums.entity.UmsMember;
import com.msb.dongbao.ums.mapper.UmsMemberMapper;
import com.msb.dongbao.ums.service.UmsMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author 晁鹏飞
 * @since 2021-01-03
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {

    @Autowired
    UmsMemberMapper umsMemberMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public String register(UserMemberDto userMemberDto){

        QueryWrapper<UmsMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userMemberDto.getUsername());
        UmsMember umsMember = umsMemberMapper.selectOne(queryWrapper);
        if(umsMember!=null&&umsMember.getUsername().length()>0)
        {
            System.out.println(umsMember.getUsername());
            return "fault";
        }

        UmsMember u = new UmsMember();

        BeanUtils.copyProperties(userMemberDto,u);
        String passwordEncoded = passwordEncoder.encode(userMemberDto.getPassword());
//        u.setPassword(DigestUtils.md5DigestAsHex(userMemberDto.getPassword().getBytes()));
        u.setPassword(passwordEncoded);
        umsMemberMapper.insert(u);

        return "success";
    }
    @Override
    public UmsMember getUserByName(String userName){
        UmsMember userMember = umsMemberMapper.selectByUsername(userName);
        if(userMember!=null)
        {
            System.out.println(userMember.toString());
            return userMember;
        }else {
            return null;
        }
    }
    @Override
    public String login(UserMemberDto userMemberDto){
        QueryWrapper<UmsMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userMemberDto.getUsername());
        UmsMember umsMember = umsMemberMapper.selectOne(queryWrapper);
        if(null != umsMember) {
            if(passwordEncoder.matches(userMemberDto.getPassword(), umsMember.getPassword())) {
                return "登录成功";
            } else {
                return "密码错误";
            }
        } else {
            return "账号不存在";
        }
    }
}
